package StudyCode.summary.csv;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ReadCSVLine {
	public static final char COLUMN_SEPARATOR = ';';
	public static final char LINE_SEPARATOR = '\n';
	private static final String[] EMPTY_ARRAY = new String[0];

	public static String[] readCsvLine(String line) throws IOException {
		return readCsvLine(line, COLUMN_SEPARATOR, LINE_SEPARATOR);
	}

	public static String[] readCsvLine(BufferedReader reader)
			throws IOException {
		return readCsvLine(reader, COLUMN_SEPARATOR, LINE_SEPARATOR);
	}

	public static String[] readCsvLine(BufferedReader reader,
	                                   char columnSeparator) throws IOException {
		return readCsvLine(reader, columnSeparator, LINE_SEPARATOR);
	}

	public static String[] readCsvLine(BufferedReader reader,
	                                   char columnSeparator, char lineSeparator) throws IOException {
		return readCsvLine(reader.readLine(), columnSeparator,
				lineSeparator);
	}

	public static String[] readCsvLine(String line, char columnSeparator,
	                                   char lineSeparator) throws IOException {

		if (line == null) {
			return EMPTY_ARRAY;
		}

		final int len = line.length();
		if (len == 0) {
			return EMPTY_ARRAY;
		}

		final List<String> result = new ArrayList<String>();

		int lastMark = 0;

		for (int i = 0; i < len; i++) {
			final char c = line.charAt(i);
			if (c == columnSeparator) {
				result.add(line.substring(lastMark, i));
				lastMark = i + 1;
			} else if (c == lineSeparator) {
				result.add(line.substring(lastMark, i));
				lastMark = len;
				break;
			}
		}

		if (lastMark < len) {
			result.add(line.substring(lastMark, len));
		}

		return result.toArray(new String[result.size()]);
	}
}
